package com.dhecp.project.system.controller;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.project.system.domain.SysRuleSet;
import com.dhecp.project.system.service.SysRuleSetService;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/system/ruleset")
public class SysRuleSetController extends BaseController {

    private String prefix = "system/ruleset";

    @Autowired
    private SysRuleSetService ruleSetService;


    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    
    /**
     * 打开规则设置列表
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:ruleset:view")
    @GetMapping()
    public ModelAndView ruleinfo(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
    	params.put("entity", new SysRuleSet()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
    	params.put("moduleTable", "TS_RuleSet");
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        AjaxResult ajaxResult = new AjaxResult();
        try{
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.setViewName(prefix + "/ruleinfo");
        return mv;
    }


    /**
     * 打开规则设置编辑页
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:ruleset:edit")
    @GetMapping("/edit")
    public ModelAndView ruleInfoEdit(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();

        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "moduleTable","规则设置表标识");
        }
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "guid","整表唯一标识");
        }
        if (mv.isEmpty()){
        	params.put("entity", new SysRuleSet());
            AjaxResult ajaxResult = new AjaxResult();
    		List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
    		List<Map<String, Object>> fieldsListTemp = new ArrayList<Map<String, Object>>(); //临时存储区，用于存放需要放到最后生成的控件，如：备注等大文本控件
            List<Object> fieldsList = new ArrayList<Object>(); 			//生成控件的字段和属性
            List<Object> fieldsHiddenList = new ArrayList<Object>(); 	//隐藏的字段和属性
        	try{
            	params.put("getFieldAttributesType", "pagenotingrid"); 	//非表格字段
        		dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
                if (dicFieldsList.isEmpty()){
                    ajaxResult = AjaxResult.error("未获取到字段属性。");
                }else{
                	SysRuleSet ruleInfo = ruleSetService.querySysRuleSetByGuid(params.get("guid").toString());
                    if (ruleInfo == null){
                        ajaxResult = AjaxResult.error("没有符合条件的数据。");
                    }else{
                        ajaxResult = AjaxResult.success("查询成功。");
                    	for (SysDictionaryForPageField dicFields : dicFieldsList){
                    		Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
                    		Map<String, Object> ruleInfoMap = TypeUtils.entityToMap(ruleInfo);
                    		fieldsListMap.put("fieldContent", ruleInfoMap.get(fieldsListMap.get("fields")));
                    		
                    		if (fieldsListMap.get("fieldFrontType") == null){
                    			fieldsListMap.put("fieldFrontType", "t_text");
                    		}
                    		
                    		if ("t_textarea".equals(fieldsListMap.get("fieldFrontType").toString())){ //大文本控件放入临时存储区
                    			fieldsListTemp.add(fieldsListMap);
                    		}else if ((Integer)fieldsListMap.get("fieldFrontTop") == 1){	//显示的字段
                    			fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                    		}else if ((Integer)fieldsListMap.get("fieldFrontTop") == 2){	//隐藏的字段
                    			fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                    		}
                    	}
                    	if (!fieldsListTemp.isEmpty() && fieldsListTemp.size() > 0){
                    		for (Map<String, Object> fieldsMap : fieldsListTemp){ 			//大文本控件追加到数组末尾
                    			if ((Integer)fieldsMap.get("fieldFrontTop") == 1){			//显示的字段
                        			fieldsList.add(TypeUtils.mapToJson(fieldsMap));
                        		}else if ((Integer)fieldsMap.get("fieldFrontTop") == 2){	//隐藏的字段
                        			fieldsHiddenList.add(TypeUtils.mapToJson(fieldsMap));
                        		}
                    		}
                    	}
                    }
                    mv.addObject("fieldsList", fieldsList);				//显示的字段
                    mv.addObject("fieldsHiddenList", fieldsHiddenList);	//隐藏的字段
                    }
        	}catch(Exception e){
        		ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        	}
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName(prefix + "/ruleinfo_add");
        }
        return mv;
    }

    /**
     * 通过传入的条件查询规则设置列表
     * @param params
     * @return GridDataModel
     * @throws Exception
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:ruleset:list")
    @RequestMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) throws Exception{
        List<SysRuleSet> list = new ArrayList<SysRuleSet>();
        try {
            list = ruleSetService.querySysRuleSetList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());   
        }
        return getDataTable(list);
    }

    /**
     * 通过guid查询规则设置单条记录
     * @param guid
     * @return MessageModel
     * @throws Exception
     * @author DH-Xxj
     */
    @RequestMapping("/lineguid")
    @ResponseBody
    public AjaxResult baseInfolineJson(@RequestParam(required = false, defaultValue = "no", value = "guid") String guid) throws Exception{
        AjaxResult ajaxResult = new AjaxResult();
        try{
        	SysRuleSet ruleInfo = ruleSetService.querySysRuleSetByGuid(guid);
            if (ruleInfo == null){
                ajaxResult =  AjaxResult.error("没有符合条件的数据。");
            }else{
                ajaxResult = AjaxResult.success("查询成功。", ruleInfo);
            }
        }catch(Exception e){
            ajaxResult =  AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 修改规则
     * @param ruleInfoItems 对应实体类的json格式字符串，示例：[{"key11":"value11","key12":"value12"},{"key21":"value21","key22":"value22"}]
     * @return MessageModel
     * @author DH-Xxj
     */
    @RequiresPermissions("system:ruleset:edit")
    @Log(title = "规则设置修改", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult ruleInfoEditPost(@RequestParam("ruleInfoItems") String ruleInfoItems) {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isEmpty(ruleInfoItems)) {
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }
        try {
            ajaxResult= ruleSetService.updateSysRuleSet(ruleInfoItems);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }


    /**
     * 修改规则设置禁用标志
     * @param ruleInfoItems 对应实体类的json格式字符串，示例：[{"key11":"value11","key12":"value12"},{"key21":"value21","key22":"value22"}]
     * @return MessageModel
     * @author DH-Xxj
     */
    @RequiresPermissions("system:ruleset:edit")
    @Log(title = "规则设置修改禁用标志", businessType = BusinessType.UPDATE)
    @PostMapping("/editbdeletedpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult ruleInfoBdeletedEditPost(@RequestParam("ruleInfoItems") String ruleInfoItems) {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isEmpty(ruleInfoItems)) {
            return AjaxResult.error("数据提交失败，必填参数有误！");
        }
        try {
            ajaxResult= ruleSetService.updateSysRuleSetBdeleted(ruleInfoItems);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
}
